#include "UsrAI.h"
#include <set>
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <bits/stdc++.h>
#include <map>
using namespace std;
tagGame tagUsrGame;
ins UsrIns;
tagInfo info;
//##################################一些数据结构########################################
//状态记录数组
vector<tagFarmer>idleFarmer;                //存储闲置的农民
vector<tagFarmer>fishingFarmer;             //存储捕鱼的农民（包含渔船）
vector<tagFarmer>cuttingFarmer;             //存储砍树的农民
vector<tagFarmer>buildingHomeFarmer;        //存储建造房子的农民
vector<tagFarmer>huntingFarmer;             //存储打猎的农民
vector<tagFarmer>buildingDockFarmer;        //存储造船坞的农民
vector<tagFarmer>cutStoneFarmer;            //存储采集石头的农民

vector<tagFarmer>buildFarmFarmer;           //存储正在建造农田的农民
vector<tagFarmer>buildNB_BuildingFarmer;    //存储正在建造高级建筑（不含仓库）的农民
vector<tagFarmer>buildStockFarmer;          //存储正在建造仓库的农民

vector<tagFarmer>boardingEnemyLandFarmer;   //存储登陆敌方大陆的农民
vector<tagArmy> boardingEnemyLandArmy;      //存储登陆敌方大陆的军队
//建立映射关系
map<int,int>SN_to_Sort;                     //资源映射
map<int,tagResource> SN_to_Resource;
map<int,int> FarmerStat;                    //村民SN->状态，村民状态映射

unordered_set<int> movingBoatSNs;           //记录正在移动的运输船SN
unordered_set<int> dockedBoatSNs;           //记录已靠岸的运输船SN
unordered_set<int> boardingFarmers;         //记录已下达登船命令的农民SN
unordered_set<int> boardingArmys;           //记录已下达登船命令的军队SN

void init_map(const tagInfo& info){
    SN_to_Sort.clear();
    SN_to_Resource.clear();         //每帧清空旧映射
    //每帧重新建立映射关系进行更新（用于记录种类信息）
    for(const tagResource& resource:info.resources){
        SN_to_Sort[resource.SN]=resource.Type; //资源种类的映射
        SN_to_Resource[resource.SN]=resource;   //记录资源完整信息
    }
    for(const tagBuilding& building:info.buildings){
        SN_to_Sort[building.SN]=building.Type; //建筑种类的映射
    }
}
//#####################################一些(静态)全局变量###############################
static bool isFirstAssigned=false;
static int firstHomeBuilderSN=-1;           //记录第一位建造房子的村民
static int firstDockBuilderSN=-1;           //记录第一位建造船坞的村民
static int firstHunterSN=-1;                //记录第一个打猎的村民
static int firstCutterSN=-1;                //记录第一个砍树的村民

static int theFarmSN=-1;                    //记录农田的SN

static int stockMAX=2;                      //己方大陆仓库数量最大值

static int Stage0_humanMax=10;
static int Stage1_humanMax=17;
static int currentHuman_N=4;                //最开始只有4个村民
static int fish_ship_Max=4;                 //最多4个渔船
static int boat_Max=2;                      //最多建3个运输船
static int ATShip_Max=12;                   //最多建12个战船
//判断市场对应的某些技术是否升级
static bool updateWoodFlag=false;           //判断伐木技术是否升级
static bool updateFarmFlag=false;           //判断农场是否升级
static bool updateStoneFlag=false;          //判断采集石头技术是否升级
static bool updateGoldFlag=false;           //判断采集金矿技术是否升级
//判断仓库对应技术是否升级
static bool UsetoolFlag=false;              //判断使用工具是否升级
static bool DefenseInfantryFlag=false;      //判断步兵护甲是否升级
static bool DefenseArcherFlag=false;        //判断弓兵护甲是否升级
static bool DefenseRiderFlag=false;         //判断骑兵护甲是否升级
//一些静态变量
char gameM[128][128];  //128x128地图块
static int centerDR=-1,centerUR=-1;         //实时地图函数中初始化市政中心坐标
static int stage=0;                         //阶段控制静态变量
//判断有关军队是否产生
static bool createClubmanFlag=false;        //判断军营生产棍棒兵
static bool createSlingerFlag=false;        //判断军营生产投石兵
static bool updateClubmanFlag=false;        //判断军营升级棍棒兵为斧头兵
static bool createBowmanFlag=false;         //判断靶场生产弓箭兵
static bool createScoutFlag=false;          //判断马厩生产骑兵
//军队数量max
static int ClubmanMax=6;                    //最多7个棍棒兵/斧头兵
static int SlingerMax=4;                    //最多4个投石兵
static int BowmanMax=2;                     //最多2个弓箭兵
static int ScoutMax=3;                      //最多3个骑兵
//判断各种船的动作是否发生
static bool toFight=false;                  //判断战船生产完毕
static bool boatToMoveFlag=false;           //判断运输船是否出发
//####################################一些辅助函数########################################
//距离计算函数
double Distance(double x1,double y1,double x2,double y2){
    return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
//获取建筑规模
enum BuildingSize {
    SIZE_1x1 = 1,
    SIZE_2x2 = 2,
    SIZE_3x3 = 3,
};
BuildingSize getBuildingSize(int buildingType) {
    switch (buildingType) {
        case BUILDING_HOME:
        case BUILDING_ARROWTOWER:
        case BUILDING_DOCK:
            return SIZE_2x2;
        case BUILDING_GRANARY:
        case BUILDING_CENTER:
        case BUILDING_STOCK:
        case BUILDING_FARM:
        case BUILDING_MARKET:
        case BUILDING_ARMYCAMP:
        case BUILDING_STABLE:
        case BUILDING_RANGE:
            return SIZE_3x3;
        default: return SIZE_1x1;                  //默认1x1格
    }
}
//获取实时地图
void realtimeMap(tagInfo info) {
    //每一帧更新时重新初始化地图
    for(int dr=0;dr<128;dr++){
            for(int ur=0;ur<128;ur++){
                gameM[dr][ur]='-';
            }
        }
        //标注地形
        for (int dr=0; dr<128; dr++){
            for (int ur = 0; ur < 128; ur++){
                const tagTerrain& ter=(*info.theMap)[dr][ur];
                if(ter.type==MAPPATTERN_OCEAN){
                    gameM[dr][ur]='-';
                }
                else if (ter.type==MAPPATTERN_GRASS) {
                    gameM[dr][ur]=ter.height+'0';  // 陆地高度（0-3）
                }else{
                    gameM[dr][ur]='?';//用？表示未探索区域
                }
            }
        }
        //标记资源（资源类型+‘A’）
        for(const tagResource& res:info.resources){
            int dr=res.BlockDR;
            int ur=res.BlockUR;
            if(dr>=0&&dr<128&&ur>=0&&ur<128){
                gameM[dr][ur]='A'+(res.Type%26);  // 区分资源类型
                if(gameM[dr][ur]=='P'){
                    gameM[dr][ur+1]='P';
                    gameM[dr+1][ur]='P';
                    gameM[dr+1][ur+1]='P';
                }
                if(res.Type==RESOURCE_STONE){
                    gameM[dr][ur]='S';
                    gameM[dr][ur+1]='S';
                    gameM[dr+1][ur]='S';
                    gameM[dr+1][ur+1]='S';
                }
                if(res.Type==RESOURCE_GOLD){
                    gameM[dr][ur]='G';
                    gameM[dr][ur+1]='G';
                    gameM[dr+1][ur]='G';
                    gameM[dr+1][ur+1]='G';
                }
                if(res.Type==RESOURCE_ELEPHANT){
                    gameM[dr][ur]='E';
                    gameM[dr][ur+1]='E';
                    gameM[dr+1][ur]='E';
                    gameM[dr+1][ur+1]='E';
                }
            }
        }
        //标记建筑（建筑类型+‘a’）
        for (const tagBuilding& building:info.buildings) {
            int dr=building.BlockDR;
            int ur=building.BlockUR;
            // 建筑占据多个块（如房屋2x2），需标记所有占用块
            int size=(building.Type==BUILDING_HOME)?2:3;  // 房屋2x2，其他3x3
            for(int i=0;i<size;i++){
                for(int j=0;j<size;j++){
                    if(dr+i<128&&ur+j<128){
                        gameM[dr+i][ur+j]='a'+(building.Type%26);
                    }
                }
            }
        }
        //标记单位位置（‘*’）
        for (const tagFarmer& farmer:info.farmers) {
                    int dr=farmer.BlockDR;
                    int ur=farmer.BlockUR;
                    if (dr>=0&&dr<128&&ur>=0&&ur<128) {
                        gameM[dr][ur]='*';
                    }
                }
        //记录市镇中心坐标
        if (centerDR==-1) {
            for (const tagBuilding& building: info.buildings) {
                if (building.Type==BUILDING_CENTER) {
                    centerDR=building.BlockDR;
                    centerUR=building.BlockUR;
                    break;
                }
            }
        }
}
//查找目标建筑是否建成
bool toFindTargetBuilding(int targetBuilding,const tagInfo& info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==targetBuilding&&building.Percent==100){
            return true;
        }
    }
    return false;
}
//查找船坞
bool toFindDock(){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_DOCK&&building.Percent==100){
            return true;
        }
    }
    return false;
}
//查询市政中心序列号
int toFindCenterSN(){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_CENTER){
            return building.SN;
        }
    }
}
//####################################一些检索函数#########################################
//检查建造地点是否合适（n*n）
bool isSuitBuilding(int x,int y,int n){
    int startX=x-1;
    int startY=y-1;
    int endX=x+n;
    int endY=y+n;
    //先检查是否越界
    if(startX<0||startY<0||endX>=128||endY>=128){
        return false;
    }
    char mapFlag=gameM[x][y];
//    if(mapFlag!='0'||mapFlag!='1'||mapFlag!='2'||mapFlag!='3'){
//        return false;
//    }
    //检查陆地高度一致性
    for(int i=startX;i<=endX;i++){
        for(int j=startY;j<=endY;j++){
            if(gameM[i][j]!=mapFlag||(gameM[i][j]!='0'&&gameM[i][j]!='1'&&gameM[i][j]!='2'&&gameM[i][j]!='3')){
                return false;
            }
        }
    }
    return true;
}
//以某一中心建筑为原点开始查找n*n的陆地空地
bool toBuildHome(int& x,int& y,int centerBuildingSN,int size,tagInfo info) {
    int n=size;
    // 查找中心建筑
    tagBuilding centerBuilding;
    bool found=false;
    for(const tagBuilding& bld:info.buildings){
        if(bld.Type==centerBuildingSN){
            centerBuilding=bld;
            found=true;
            break;
        }
    }
    if(!found){// 未找到中心建筑
        return false;
    }
    // 获取中心建筑的大小
    BuildingSize centerSize=getBuildingSize(centerBuilding.Type);
    // 计算中心坐标（取建筑中心）
    int center_x=centerBuilding.BlockDR+centerSize/2;
    int center_y=centerBuilding.BlockUR+centerSize/2;
    //搜索适合建造n*n大小的建筑
    const int misRange=3;
    const int maxRange=20;
    //第一象限
    for(int i=center_x+misRange;i<=center_x+maxRange;i++){
        for(int j=center_y+misRange;j<=center_y+maxRange;j++){
            if(isSuitBuilding(i,j,n)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    //第二象限
    for(int i=center_x-misRange;i>=center_x-maxRange;i--){
        for(int j=center_y+misRange;j<=center_y+maxRange;j++){
            if(isSuitBuilding(i,j,n)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    //第三象限
    for(int i=center_x-misRange;i>=center_x-maxRange;i--){
        for(int j=center_y-misRange;j>=center_y-maxRange;j--){
            if(isSuitBuilding(i,j,n)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    //第四象限
    for(int i=center_x+misRange;i<=center_x+maxRange;i++){
        for(int j=center_y-misRange;j>=center_y-maxRange;j--){
            if(isSuitBuilding(i,j,n)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    return false;
}
//检查建造船坞的地点是否都为海洋
bool isSuitDock(int x,int y){
    //先检查是否越界
    if(x<0||y<0||x+1>=128||y+1>=128){
        return false;
    }
    //判断是否为海洋
    char dock_flag=gameM[x][y];
    if(dock_flag!='-'){
        return false;
    }
    if(gameM[x+1][y]==dock_flag&&gameM[x+1][y+1]==dock_flag
            &&gameM[x][y+1]==dock_flag){
        if((gameM[x-1][y]>='0'&&gameM[x-1][y]<='3')||(gameM[x-1][y+1]>='0'&&gameM[x-1][y+1]<='3')
            ||(gameM[x+2][y]>='0'&&gameM[x+2][y]<='3')||(gameM[x+2][y+1]>='0'&&gameM[x+2][y+1]<='3')
            ||(gameM[x][y-1]>='0'&&gameM[x][y-1]<='3')||(gameM[x][y+2]>='0'&&gameM[x][y+2]<='3')
            ||(gameM[x+1][y-1]>='0'&&gameM[x+1][y-1]<='3')||(gameM[x+1][y+2]>='0'&&gameM[x+1][y+2]<='3')){
            return true;
        }
    }
//    if(gameM[x-1][y]=='P'||gameM[x-1][y+1]=='P'||gameM[x+2][y]=='P'||gameM[x+2][y+1]=='P'||
//            gameM[x][y-1]=='P'||gameM[x][y+2]=='P'||gameM[x+1][y-1]=='P'||gameM[x+1][y+2]=='P'){
//        return false;
//    }
    return false;
}
//以某一鱼塘为中心原点开始查找适合建造船坞的地点
bool toBuildDock(int& x,int& y,tagInfo info){
    //先查找鱼塘
    bool pond_flag=false;
    int pond_x=-1,pond_y=-1;    //初始化鱼塘坐标（目前还没有找到）
    for(tagResource& resource:info.resources){
        if(resource.Type==RESOURCE_FISH&&resource.Cnt>0){
            pond_x=resource.BlockDR;
            pond_y=resource.BlockUR;
            pond_flag=true;
            break;
        }
    }
    if(!pond_flag) return false;    //如果没有找到鱼塘
    const int minRange=3;
    const int maxRange=17;
    //第一象限
    for(int i=pond_x+minRange;i<=pond_x+maxRange;i++){
        for(int j=pond_y+minRange;j<=pond_y+maxRange;j++){
            if(isSuitDock(i,j)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    //第二象限
    for(int i=pond_x-minRange;i>=pond_x-maxRange;i--){
        for(int j=pond_y+minRange;j<=pond_y+maxRange;j++){
            if(isSuitDock(i,j)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    //第三象限
    for(int i=pond_x-minRange;i>=pond_x-maxRange;i--){
        for(int j=pond_y-minRange;j>=pond_y-maxRange;j--){
            if(isSuitDock(i,j)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    //第四象限
    for(int i=pond_x+minRange;i<=pond_x+maxRange;i++){
        for(int j=pond_y-minRange;j>=pond_y-maxRange;j--){
            if(isSuitDock(i,j)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    return false;
}
//农民状态判断函数
void judgeFarmerState(const tagInfo& info) {
    idleFarmer.clear();
    fishingFarmer.clear();
    cuttingFarmer.clear();
    huntingFarmer.clear();
    buildingHomeFarmer.clear();
    buildFarmFarmer.clear();
    buildingDockFarmer.clear();
    cutStoneFarmer.clear();
    buildNB_BuildingFarmer.clear();
    buildStockFarmer.clear();
    FarmerStat.clear();

    for(const tagFarmer& farmer:info.farmers){
        FarmerStat[farmer.SN]=farmer.NowState; //记录状态
        if(farmer.SN==firstHomeBuilderSN||farmer.SN==firstDockBuilderSN||
           farmer.SN==firstCutterSN||farmer.SN==firstHunterSN) {
            continue;
        }
        //渔船工作对象无效，标记为需要新任务
        if(farmer.FarmerSort==2){
            if(farmer.NowState==HUMAN_STATE_WORKING){
                int workSN=farmer.WorkObjectSN;
                if(SN_to_Resource.count(workSN)&&SN_to_Resource[workSN].Cnt <= 0) {
                    idleFarmer.push_back(farmer); //视为空闲，等待新任务
                    continue;
                }
            }else if(farmer.NowState==HUMAN_STATE_IDLE){
                idleFarmer.push_back(farmer);
            }
            continue;
        }

        if(farmer.NowState==HUMAN_STATE_IDLE){
            idleFarmer.push_back(farmer);
            continue;
        }else if(farmer.NowState==HUMAN_STATE_WORKING){
            int workSN=farmer.WorkObjectSN;
            if(SN_to_Sort.count(workSN)){
                int resType=SN_to_Sort[workSN];
                // 根据工作对象类型归类
                if(resType==RESOURCE_FISH&&farmer.FarmerSort==2){
                    fishingFarmer.push_back(farmer);
                }else if(resType==RESOURCE_TREE&&farmer.FarmerSort==0){
                    cuttingFarmer.push_back(farmer);
                }else if(resType==RESOURCE_GAZELLE&&farmer.FarmerSort==0){
                    huntingFarmer.push_back(farmer);
                }else if(resType==BUILDING_HOME&&farmer.FarmerSort==0){
                    buildingHomeFarmer.push_back(farmer);
                }else if(resType==BUILDING_DOCK&&farmer.FarmerSort==0){
                    buildingDockFarmer.push_back(farmer);
                }else if(resType==RESOURCE_STONE&&farmer.FarmerSort==0){
                    cutStoneFarmer.push_back(farmer);
                }else if(resType==BUILDING_FARM&&farmer.FarmerSort==0){
                    buildFarmFarmer.push_back(farmer);
                }else if((resType==BUILDING_MARKET||resType==BUILDING_GRANARY)&&farmer.FarmerSort==0){
                    buildNB_BuildingFarmer.push_back(farmer);
                }else if(resType==BUILDING_STOCK&&farmer.FarmerSort==0){
                    buildStockFarmer.push_back(farmer);
                }
            }
        }
    }
}
//寻找最近的资源（返回最近的目标资源种类序列号）
int findResource(const tagFarmer& farmer,int targetType,const tagInfo& info){
        double minDis=1e12;
        int closestSN=-1;
        double tempDis;
        // 遍历所有资源
        for(const tagResource& resource:info.resources){
            if(resource.Type!=targetType){
                continue;
            }
            if(resource.Cnt<=0){
                continue;
            }
            if(resource.BlockDR<0||resource.BlockDR>=128||resource.BlockUR<0||resource.BlockUR>=128){
                continue;
            }
            const tagTerrain& terrain=(*info.theMap)[resource.BlockDR][resource.BlockUR];
            if(terrain.type==MAPPATTERN_UNKNOWN){
                continue;
            }
            tempDis=Distance(farmer.DR,farmer.UR,resource.DR,resource.UR);
            // 更新最近资源
            if(tempDis<minDis){
                minDis=tempDis;
                closestSN=resource.SN;
            }
        }
        return closestSN;
}
//#####################################任务分配函数###########################################
//判断是否还有瞪羚剩余
bool isGazelle(const tagInfo& info){
    for(const tagResource& resource:info.resources){
        if(resource.Type==RESOURCE_GAZELLE&&resource.Cnt>=0){
            return true;
        }
    }
    return false;
}
//对最开始的4位村民进行任务分配
void UsrAI::assignFirstTask(const tagInfo &info){
    if(isFirstAssigned||info.farmers.size()!=4) return;
    for(int i=0;i<4;i++){
        const tagFarmer& myFarmer=info.farmers[i];
        if(myFarmer.NowState!=HUMAN_STATE_IDLE) continue;
        if(i==0&&myFarmer.FarmerSort==0){   //让第一位村民建房子
            int x,y;
            if(toBuildHome(x,y,BUILDING_CENTER,2,info)&&info.Wood>=BUILD_HOUSE_WOOD){
                HumanBuild(myFarmer.SN,BUILDING_HOME,x,y);
                firstHomeBuilderSN=myFarmer.SN;
            }
        }else if(i==1&&myFarmer.FarmerSort==0){   //让第二个村民造船坞
            int dockX,dockY;
            if(toBuildDock(dockX,dockY,info)&&info.Wood>=BUILD_DOCK_WOOD){
                HumanBuild(myFarmer.SN,BUILDING_DOCK,dockX,dockY);
                firstDockBuilderSN=myFarmer.SN;
            }
        }else if(i==2&&myFarmer.FarmerSort==0){   //第三个村民去砍树
            int treeSN=-1;
            treeSN=findResource(myFarmer,RESOURCE_TREE,info);
            if(treeSN!=-1){
                HumanAction(myFarmer.SN,treeSN);
                firstCutterSN=myFarmer.SN;
            }
        }else if(i==3&&myFarmer.FarmerSort==0){     //让第四个村民去打猎
             int huntSN=-1;
             huntSN=findResource(myFarmer,RESOURCE_GAZELLE,info);
             if(huntSN!=-1){
                 HumanAction(myFarmer.SN,huntSN);
                 firstHunterSN=myFarmer.SN;
             }
        }
    }
    isFirstAssigned=true;
}
//##########################################检索各种船的数量####################################
//检索渔船数量
bool isToBuildFish_ship(const tagInfo& info){
    bool toBuildFishShip_flag=false;
    int currentFishShip_N=0;
    for(const tagFarmer& fishFaremer:info.farmers){
        if(fishFaremer.FarmerSort==2){
            currentFishShip_N++;
        }
    }
    if(currentFishShip_N<fish_ship_Max){
        toBuildFishShip_flag=true;
    }
    return toBuildFishShip_flag;
}
//检索运输船数量
bool isToBuildBoat(const tagInfo& info){
    bool toBuildBoat_flag=false;
    int currentBoat_N=0;
    for(const tagFarmer& boat:info.farmers){
        if(boat.FarmerSort==1){
            currentBoat_N++;
        }
    }
    if(currentBoat_N<boat_Max){
        toBuildBoat_flag=true;
    }
    return toBuildBoat_flag;
}
//检索战船数量
bool isToBuildATShip(const tagInfo& info){
    bool toBuildATShip_flag=false;
    int currentATShip_N=0;
    for(const tagArmy& ATship:info.armies){
        if(ATship.Sort==7){
            currentATShip_N++;
        }
    }
    if(currentATShip_N<ATShip_Max){
        toBuildATShip_flag=true;
    }
    return toBuildATShip_flag;
}
//#############################################################################################
//最开始打猎和砍树的村民继续之前的任务
void UsrAI::goWork_hunt(const tagInfo &info){
    if(firstHunterSN==-1) return;
    for(const tagFarmer& farmer:info.farmers){
        if(farmer.SN==firstHunterSN&&farmer.NowState==HUMAN_STATE_IDLE){
            if(isGazelle(info)){
                int nextGazelle=findResource(farmer,RESOURCE_GAZELLE,info);
                if(nextGazelle!=-1){
                    HumanAction(farmer.SN,nextGazelle);
                }
            }else{
                int nextTreeSN=findResource(farmer,RESOURCE_TREE,info);
                if(nextTreeSN!=-1){
                    HumanAction(farmer.SN,nextTreeSN);
                }
            }
        }
        break;
    }
}
void UsrAI::goWork_cut(const tagInfo &info){
    if(firstCutterSN==-1) return;
    for(const tagFarmer& farmer:info.farmers){
        if(farmer.SN==firstCutterSN&&farmer.NowState==HUMAN_STATE_IDLE){
            int nextTreeSN=findResource(farmer,RESOURCE_TREE,info);
            if(nextTreeSN!=-1){
                HumanAction(farmer.SN,nextTreeSN);
            }
        }
        break;
    }
}
//让最开始建房子和建造船坞的村民继续建造其他建筑
bool isGoWork(int buildType,const tagInfo& info,int num_max){
    int currentNum=0;
    for (const auto& bld:info.buildings) {
        if(bld.Type==buildType&&bld.Percent==100){
            currentNum++;
        }
    }
    if(buildType==BUILDING_HOME){
        return currentNum<num_max;//最多home_max个房子
    }else if(buildType==BUILDING_DOCK){
        return currentNum<num_max;//最多两个船坞
    }else if(buildType==BUILDING_GRANARY){
        return currentNum<num_max;//最多一个谷仓
    }else if(buildType==BUILDING_FARM){
        return currentNum<num_max;//最多一个农田
    }else if(buildType==BUILDING_MARKET){
        return currentNum<num_max;//最多一个市场
    }else if(buildType==BUILDING_STOCK){
        return currentNum<num_max;//最多两个仓库
    }else if(buildType==BUILDING_ARMYCAMP){
        return currentNum<num_max;//最多一个军营
    }else if(buildType==BUILDING_RANGE){
        return currentNum<num_max;//最多一个靶场
    }else if(buildType==BUILDING_STABLE){
        return currentNum<num_max;//最多一个马厩
    }
    return false;
}
void UsrAI::goWork_build_dock(tagInfo& info,int num_max){
    int num=num_max;
    //继续建船坞
    if(firstDockBuilderSN!=-1){
        for(tagFarmer& farmer:info.farmers){
            if(farmer.SN==firstDockBuilderSN&&farmer.NowState==HUMAN_STATE_IDLE){
                if(info.Wood>=BUILD_DOCK_WOOD&&isGoWork(BUILDING_DOCK,info,num)){
                    int dockX,dockY;
                    if(toBuildDock(dockX,dockY,info)){
                        HumanBuild(farmer.SN,BUILDING_DOCK,dockX,dockY);
                        break;
                    }
                }
            }
        }
    }   
}
void UsrAI::goWork_build_home(const tagInfo& info,int num_max){
    int num=num_max;
    //继续建房子
    if(firstHomeBuilderSN!=-1){
        for(const tagFarmer& farmer:info.farmers){
            if(farmer.SN==firstHomeBuilderSN&&farmer.NowState==HUMAN_STATE_IDLE){
                if(info.Wood>=BUILD_HOUSE_WOOD&&isGoWork(BUILDING_HOME,info,num)){
                    int x,y;
                    if(toBuildHome(x,y,BUILDING_CENTER,2,info)){
                        HumanBuild(farmer.SN,BUILDING_HOME,x,y);
                    }
                }
                break;
            }
        }
    }
}
//stage1中让建造船坞的村民去建房屋（任务转换）
void UsrAI::buildDockToBuildhome(tagInfo &info,int num_max){
    int num=num_max;
    if(firstDockBuilderSN!=-1){
        for(tagFarmer& farmer:info.farmers){
            if(farmer.SN==firstDockBuilderSN){
                if(info.Wood>=BUILD_HOUSE_WOOD&&isGoWork(BUILDING_HOME,info,num)&&farmer.NowState==HUMAN_STATE_IDLE){
                    int x,y;
                    if(toBuildHome(x,y,BUILDING_CENTER,2,info)){
                        HumanBuild(farmer.SN,BUILDING_HOME,x,y);
                    }
                }
                break;
            }
        }
    }
}
// 不断地分配任务
void UsrAI::assignNewTask(const tagInfo &info) {
    int huntingLimit=3;  //最多分配3个村民去打猎
    int huntingAssigned=huntingFarmer.size();  //已经分配打猎任务的村民数量
    for(const tagFarmer& myFarmer:info.farmers){
        if(myFarmer.FarmerSort!=0) continue;  //只处理村民
        if(myFarmer.NowState!=HUMAN_STATE_IDLE) continue;  //只处理空闲村民
        //跳过初始村民
        if(myFarmer.SN==firstHomeBuilderSN||myFarmer.SN==firstDockBuilderSN||
            myFarmer.SN==firstCutterSN||myFarmer.SN==firstHunterSN){
            continue;
        }
        //如果还没有分配足够的打猎任务，则分配打猎
        if(huntingAssigned<huntingLimit){
            int huntSN=findResource(myFarmer,RESOURCE_GAZELLE,info);
            if(huntSN!=-1){
                HumanAction(myFarmer.SN,huntSN);
                huntingAssigned++;  //增加已分配打猎任务的村民数量
            }
        }else{  //如果打猎任务已满，转去砍树
            int treeSN=findResource(myFarmer,RESOURCE_TREE,info);
            if (treeSN!=-1){
                HumanAction(myFarmer.SN,treeSN);
            }
        }
    }
}
//stage1中的持续任务分配（除了初始的全部去砍树）
void UsrAI::assignNewTaskInStage1(const tagInfo &info){
    for(const tagFarmer& myFarmer:info.farmers){
        if(myFarmer.FarmerSort!=0) continue;
        if(myFarmer.NowState!=HUMAN_STATE_IDLE) continue;
        //跳过初始村民
        if(myFarmer.SN==firstHomeBuilderSN||myFarmer.SN==firstDockBuilderSN||myFarmer.SN==firstCutterSN){
            continue;
         }
        //除了初始的全部去砍树
        if(cuttingFarmer.size()<15){
            int treeSN=findResource(myFarmer,RESOURCE_TREE,info);
            if(treeSN!=-1){
                HumanAction(myFarmer.SN,treeSN);
            }
        }
    }
}
//####################################stage1中的任务分配###################################
//指定数量为num的村民去砍树
void UsrAI::farmerToCut(const tagInfo &info,int num){
    int need=num-cuttingFarmer.size();
    if(need<=0) return;

    int treeSN=-1;
    int assigned=0;//记录已分配任务的村民数量
    for(const tagFarmer& farmer:info.farmers){
        if(farmer.SN==firstHomeBuilderSN) continue;
        if(assigned>=need) break;
        if(farmer.FarmerSort==0&&farmer.NowState==HUMAN_STATE_IDLE){
            treeSN=findResource(farmer,RESOURCE_TREE,info);
            if(treeSN!=-1){
                HumanAction(farmer.SN,treeSN);
                assigned++;
            }
        }
    }
}
//指定数量为num的村民打猎
void UsrAI::farmerToHunt(const tagInfo &info,int num){
    int need=num-huntingFarmer.size();
    if(need<=0) return;

    int gazelleSN=-1;
    int assigned=0;//记录已分配任务的村民数量
    for(const tagFarmer& farmer:info.farmers){
        if(farmer.SN==firstHunterSN||farmer.SN==firstHomeBuilderSN||farmer.SN==firstDockBuilderSN) continue;
        if(assigned>=need) break;
        if(farmer.FarmerSort==0&&farmer.NowState==HUMAN_STATE_IDLE){
            gazelleSN=findResource(farmer,RESOURCE_GAZELLE,info);
            if(gazelleSN!=-1){
                HumanAction(farmer.SN,gazelleSN);
                assigned++;
            }
        }
    }
}
//指定数量为num的村民采集石头
void UsrAI::farmerToStone(const tagInfo &info,int num){
    int need=num-cutStoneFarmer.size();
    if(need<=0) return;

    int stoneSN=-1;
    int assigned=0;//记录已分配任务的村民数量
    for(const tagFarmer& farmer:info.farmers){
        if(assigned>=need) break;
        if(farmer.FarmerSort==0&&farmer.NowState==HUMAN_STATE_IDLE){
            stoneSN=findResource(farmer,RESOURCE_STONE,info);
            if(stoneSN!=-1){
                HumanAction(farmer.SN,stoneSN);
                assigned++;
            }
        }
    }
}
//指定村民去采集金矿
void UsrAI::farmerToGold(const tagInfo &info){
    int goldSN=-1;
    for(const tagFarmer& farmer:boardingEnemyLandFarmer){
        if(farmer.SN==firstHunterSN||farmer.SN==firstHomeBuilderSN||farmer.SN==firstDockBuilderSN) continue;
        if(farmer.FarmerSort==0&&farmer.NowState==HUMAN_STATE_IDLE){
            goldSN=findResource(farmer,RESOURCE_GOLD,info);
            if(goldSN!=-1){
                HumanAction(farmer.SN,goldSN);
            }
        }
    }
}
//stage2中让num位村民去建造农田
void UsrAI::farmerToBuildFarmAfterStage0(const tagInfo &info,int num){
    int need=num-buildFarmFarmer.size();
    if(need<=0) return;

    int assigned=0;
    for(const tagFarmer& farmer:info.farmers){
        if(farmer.SN==firstCutterSN||farmer.SN==firstHomeBuilderSN) continue;
        if(assigned>=need) break;
        if(farmer.FarmerSort==0&&farmer.NowState==HUMAN_STATE_IDLE){
            int x,y;
            if(info.Wood>=BUILD_FARM_WOOD&&isGoWork(BUILDING_FARM,info,num)){
                if(toBuildHome(x,y,BUILDING_CENTER,3,info)){
                    HumanBuild(farmer.SN,BUILDING_FARM,x,y);
                    assigned++;
                }
            }
            break;
        }
    }
}
//让最开始建造船坞的村民在建完dock_num个船坞后去砍树
void UsrAI::buildDockToCut(const tagInfo &info,int dock_num){
    int treeSN=-1;
    if(firstDockBuilderSN!=-1){
        for(const tagFarmer& farmer:info.farmers){
            if(farmer.SN==firstDockBuilderSN&&farmer.NowState==HUMAN_STATE_IDLE){
                if(!isGoWork(BUILDING_DOCK,info,dock_num)){
                    treeSN=findResource(farmer,RESOURCE_TREE,info);
                    if(treeSN!=-1){
                        HumanAction(farmer.SN,treeSN);
                    }
                }
            }
        }
    }
}
//建造仓库
bool toBuildStock(int& x,int& y,int size,const tagInfo& info){
    int center_x,center_y;
    for(const tagResource& resource:info.resources){
        if(resource.Type==RESOURCE_GAZELLE){
            center_x=resource.BlockDR;
            center_y=resource.BlockUR;
            break;
        }
    }
    const int minRange=2;
    const int maxRange=9;
    //第一象限
    for(int i=center_x+minRange;i<=center_x+maxRange;i++){
        for(int j=center_y+minRange;j<=center_y+maxRange;j++){
            if(isSuitBuilding(i,j,size)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    //第二象限
    for(int i=center_x-minRange;i>=center_x-maxRange;i--){
        for(int j=center_y+minRange;j<=center_y+maxRange;j++){
            if(isSuitBuilding(i,j,size)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    //第三象限
    for(int i=center_x-minRange;i>=center_x-maxRange;i--){
        for(int j=center_y-minRange;j>=center_y-maxRange;j--){
            if(isSuitBuilding(i,j,size)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    //第四象限
    for(int i=center_x+minRange;i<=center_x+maxRange;i++){
        for(int j=center_y-minRange;j>=center_y-maxRange;j--){
            if(isSuitBuilding(i,j,size)){
                x=i;
                y=j;
                return true;
            }
        }
    }
    return false;
}
void UsrAI::ToBuildStock(const tagInfo &info){
    for(const tagFarmer& farmer:info.farmers){
        if(farmer.SN==firstCutterSN||farmer.SN==firstDockBuilderSN||
        farmer.SN==firstHomeBuilderSN||farmer.SN==firstHunterSN) continue;
        if(farmer.NowState==HUMAN_STATE_IDLE){
            int x,y;
            if(toBuildStock(x,y,3,info)&&isGoWork(BUILDING_STOCK,info,stockMAX)){
                if(info.Wood>=BUILD_STOCK_WOOD){
                    HumanBuild(farmer.SN,BUILDING_STOCK,x,y);
                    break;
                }
            }
        }
    }
}
//让建房屋的村民在完成阶段任务后去砍树
void UsrAI::buildHomeToCut(const tagInfo &info,int stage0_home_max){
    int treeSN=-1;
    if(firstHomeBuilderSN!=-1){
        for(const tagFarmer& farmer:info.farmers){
            if(farmer.SN==firstHomeBuilderSN&&farmer.NowState==HUMAN_STATE_IDLE){
                if(!isGoWork(BUILDING_HOME,info,stage0_home_max)){
                    treeSN=findResource(farmer,RESOURCE_TREE,info);
                    if(treeSN!=-1){
                        HumanAction(farmer.SN,treeSN);
                    }
                }
            }
        }
    }
}
//建造高级的建筑(3*3),由最开始建房子的村民去建造
void UsrAI::buildNB_buildings(const tagInfo& info,int targetBuilding,int num_max){
    if(firstHomeBuilderSN!=-1){
        for(const tagFarmer& farmer:info.farmers){
            if(farmer.SN==firstHomeBuilderSN){
                if(farmer.NowState==HUMAN_STATE_IDLE){
                    int x,y;
                    if(toBuildHome(x,y,BUILDING_CENTER,3,info)&&isGoWork(targetBuilding,info,num_max)){
                        HumanBuild(farmer.SN,targetBuilding,x,y);
                    }
                }
            }
        }
    }
}
//########################################################################################
//查询农田SN
int findFarmSN(const tagInfo& info){
    int farmSN=-1;
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_FARM&&building.Percent==100){
            farmSN=building.SN;
        }
    }
    return farmSN;
}
//继续种地
void UsrAI::goWork_farming(const tagInfo &info){
    theFarmSN=findFarmSN(info);
    if(firstHomeBuilderSN!=-1&&theFarmSN!=-1){
        for(const tagFarmer& farmer:info.farmers){
            if(farmer.SN==firstHomeBuilderSN&&farmer.NowState==HUMAN_STATE_IDLE){
                HumanAction(farmer.SN,theFarmSN);
            }
        }
    }
}
//#####################################船坞的一些动作#######################################
//船坞造渔船
void UsrAI::buildFish_ship(const tagInfo &info){
    int dockSN=-1;
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_DOCK&&building.Percent==100){
            dockSN=building.SN;
        }
    }
    if(dockSN!=-1){
        BuildingAction(dockSN,BUILDING_DOCK_CREATE_SAILING);
    }
}
//检索船坞的坐标
pair<int,int> findDockPos(const tagInfo& info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_DOCK&&building.Percent==100){
            return {building.BlockDR,building.BlockUR};
        }
    }
    return {-1,-1};                                                 //未找到
}
//判断指定块是否为己方陆地
bool isOurLand(const tagInfo& info,int blockDR,int blockUR){
    if(blockDR< 0||blockDR>=128||blockUR<0||blockUR>=128) return false;
    const tagTerrain& terrain=(*info.theMap)[blockDR][blockUR];
    //己方陆地定义为已探索的草地
    return terrain.type==MAPPATTERN_GRASS;
}
//判断海洋块是否为沿岸（周围3x3范围内有己方陆地）
bool isCoastalOcean(const tagInfo& info,int blockDR,int blockUR){
    //判断当前块是否为海洋且已探索
    if(blockDR<0||blockDR>=128||blockUR<0||blockUR>=128) return false;
    const tagTerrain& terrain =(*info.theMap)[blockDR][blockUR];
    if (terrain.type != MAPPATTERN_OCEAN) return false;
    //检查周围3x3范围内是否有己方陆地
    for(int dx=-1;dx<=1;dx++) {
        for(int dy=-1;dy<=1;dy++){
            if(dx==0&&dy==0) continue; //跳过自身
            if(isOurLand(info,blockDR+dx,blockUR+dy)){
                return true;
            }
        }
    }
    return false;
}
//查找距离船坞最远的己方沿岸海洋块坐标（块坐标）
pair<int, int> findMaxCoastalOcean(const tagInfo& info) {
    //获取船坞坐标
    pair<int, int> dockPos=findDockPos(info);
    if (dockPos.first==-1||dockPos.second==-1){
        return {-1,-1}; //船坞不存在
    }
    int dockDR=dockPos.first;
    int dockUR=dockPos.second;
    //遍历所有地图块，筛选沿岸海洋块并计算最远距离
    pair<int, int>MaxOcean ={-1,-1};
    double maxDistance=-1.0;
    for(int dr=0;dr<128;dr++){ //遍历所有BlockDR
        for(int ur=0;ur<128;ur++){ //遍历所有BlockUR
            //检查是否为沿岸海洋块
            if(isCoastalOcean(info,dr,ur)){
                //计算与船坞的距离
                double distance=sqrt(pow(dr-dockDR,2)+pow(ur-dockUR,2));
                //更新最远距离
                if(distance>maxDistance){
                    maxDistance=distance;
                    MaxOcean={dr,ur};
                }
            }
        }
    }
    return MaxOcean;
}
//渔船捕鱼
void UsrAI::ship_to_fish(const tagInfo &info){
    unordered_set<int> assignedFishSNs;             //记录当前已分配的鱼资源SN，避免重复分配
    for(const tagFarmer& boat:info.farmers){
        if(boat.FarmerSort!=2||boat.NowState!=HUMAN_STATE_IDLE){
            continue;                               //非渔民或非空闲状态，跳过
        }
        //寻找最近的、未分配的、有效鱼资源
        int min_SN=-1;
        double min_dis=1e9;
        for(const tagResource& resource:info.resources) {
            if (resource.Type!=RESOURCE_FISH) continue;
            if (resource.Cnt<=0) continue;                          //资源未耗尽
            if (assignedFishSNs.count(resource.SN)) continue;       //未被当前轮次的其他渔民分配
            //计算渔民到鱼资源的距离
            double dis=Distance(boat.DR, boat.UR, resource.DR, resource.UR);
            if (dis<min_dis) {
                min_dis=dis;
                min_SN=resource.SN;
            }
        }
        //若找到有效资源，分配任务并标记为已分配
        if(min_SN!=-1){
            HumanAction(boat.SN, min_SN);
            assignedFishSNs.insert(min_SN); //将资源SN加入已分配集合
        }else{
            pair<int,int> exploreBlock=findMaxCoastalOcean(info);
            int exploreX=exploreBlock.first;
            int exploreY=exploreBlock.second;
            if(exploreX!=-1){
                HumanMove(boat.SN,exploreX*BLOCKSIDELENGTH,exploreY*BLOCKSIDELENGTH);
                break;
            }
        }
    }
}
//船坞造运输船
void UsrAI::buildBoat(const tagInfo &info){
    int dockSN=-1;
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_DOCK&&building.Percent==100){
            dockSN=building.SN;
        }
    }
    if(dockSN!=-1){
        BuildingAction(dockSN,BUILDING_DOCK_CREATE_WOOD_BOAT);
    }
}
//船坞造战船
void UsrAI::buildATShip(const tagInfo &info){
    int dockSN=-1;
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_DOCK&&building.Percent==100){
            dockSN=building.SN;
        }
    }
    if(dockSN!=-1){
        BuildingAction(dockSN,BUILDING_DOCK_CREATE_SHIP);
    }
}
//###################################战船的一些动作#########################################
//自动锁敌攻击敌军
void UsrAI::fightingEnermy(const tagInfo &info){
    vector<tagArmy> firstAttack;
    vector<tagArmy> secondAttack;
    for(const tagArmy& enemy:info.enemy_armies){
        if((enemy.Sort==AT_SHIP||enemy.Sort==0||enemy.Sort==1||enemy.Sort==2||enemy.Sort==3||enemy.Sort==4)&&enemy.Blood>0){
            if(enemy.Sort!=AT_BOWMAN){
                firstAttack.push_back(enemy);
            }else{
                secondAttack.push_back(enemy);
            }
        }
    }
    for(const tagArmy& enemy:firstAttack){
        for(const tagArmy& ourATship:info.armies){
            if(ourATship.Sort==AT_SHIP&&(ourATship.NowState==HUMAN_STATE_WALKING||ourATship.NowState==HUMAN_STATE_IDLE)){
                HumanAction(ourATship.SN,enemy.SN);
            }
        }
    }
    if(firstAttack.size()<=1||firstAttack.empty()){
        for(const tagArmy& enemy:info.enemy_armies){
            for(const tagArmy& ourATship:info.armies){
                if(ourATship.Sort==AT_SHIP&&(ourATship.NowState==HUMAN_STATE_WALKING||ourATship.NowState==HUMAN_STATE_IDLE)){
                    HumanAction(ourATship.SN,enemy.SN);
                }
            }
        }
    }
}
//寻找敌方大陆坐标
void UsrAI::findEnermyRoute(const tagInfo &info,int& enermyLand_x,int& enermyLand_y){
    enermyLand_x=-1;
    enermyLand_y=-1;
    int x=-1,y=-1;
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_CENTER){
            x=building.BlockDR;
            y=building.BlockUR;
            break;
        }
    }
    enermyLand_x=(x<64)?100:25;
    enermyLand_y=(y<64)?100:25;
}
//战船前往敌方大陆
void UsrAI::moveToEnermyLand(const tagInfo &info){
    int enermyLand_x=-1,enermyLand_y=-1;
    findEnermyRoute(info,enermyLand_x,enermyLand_y);
    for(const tagArmy& ourShip:info.armies){
        if(ourShip.Sort==AT_SHIP&&ourShip.NowState==HUMAN_STATE_IDLE){
            HumanMove(ourShip.SN,enermyLand_x*BLOCKSIDELENGTH,enermyLand_y*BLOCKSIDELENGTH);
            break;
        }
    }
}
//#####################################运输船的动作##########################################################
//################################运输船在己方大陆进行靠岸#######################################
//获取已有运输船的坐标（避免运输船之间位置太近）
vector<pair<int,int>> getBoatPos(const tagInfo& info){
    vector<pair<int,int>> pos;
    for(const tagFarmer& myBoat:info.farmers){
        if(myBoat.FarmerSort==1){
            pos.emplace_back(myBoat.BlockDR,myBoat.BlockUR);
        }
    }
    return pos;
}
//检索船坞附近的沿岸坐标
pair<int,int> findNearLandPosForBoat(const tagInfo& info,int dockDR,int dockUR,const vector<pair<int,int>>& usePos){
    const int findRange=7;
    const int safeDistance=3;
    vector<pair<int,int>> candidates;                               //存储所有符合条件的候选位置
    for(int x=dockDR-findRange;x<=dockDR+findRange;x++){
        for(int y=dockUR-findRange;y<=dockUR+findRange;y++){
            if(x<0||x>=128||y<0||y>=128) continue;                  //越界检查
            if(gameM[x][y]!='-') continue;                          //检查是否为海洋
            //防重叠检测
            bool isOccupied=false;
            for(const auto& position:usePos){
                int dx=abs(x-position.first);
                int dy=abs(y-position.second);
                if(dx<safeDistance&&dy<safeDistance){
                    isOccupied=true;
                    break;
                }
            }
            if(isOccupied) continue;
            //检查是否沿岸
            bool isNearLand=false;
            for(int i=x-1;i<=x+1;i++){
                for(int j=y-1;j<=y+1;j++){
                    if(i<0||i>=128||j<0||j>=128) continue;
                    if(i==x&&j==y) continue;
                    if(gameM[i][j]=='S') continue;
                    if(gameM[i][j]>='0'&&gameM[i][j]<='3'){
                        isNearLand=true;
                        break;
                    }
                }
                if(isNearLand) break;
            }
            if(isNearLand){
                candidates.emplace_back(x,y);                           //符合条件的位置加入候选列表
            }
        }
    }
    //从候选位置中筛选出离陆地最近的位置
        if(candidates.empty()){
            return {-1,-1};                                             //无符合条件的位置
        }

        pair<int,int> bestPos={-1,-1};
        int minDistance=INT_MAX;                                        //记录最近距离（曼哈顿距离）

        for(const auto& pos:candidates){
            int x=pos.first;
            int y=pos.second;
            int currentMin=INT_MAX;
            //计算当前位置到最近陆地的曼哈顿距离
            for(int i=x-2;i<=x+2;i++){                                  //扩大搜索范围确保找到最近陆地
                for(int j=y-2;j<=y+2;j++){
                    if(i<0||i>=128||j<0||j>=128) continue;
                    if(gameM[i][j]>='0'&&gameM[i][j]<='3'){
                        int dist=abs(x-i)+abs(y-j);                     //曼哈顿距离
                        if(dist<currentMin){
                            currentMin=dist;
                        }
                    }
                }
            }
            //更新最近陆地的位置
            if(currentMin<minDistance){
                minDistance=currentMin;
                bestPos=pos;
            }
        }
        return bestPos;                                                 //返回离陆地最近的位置
}
//运输船移动至己方大陆沿岸
void UsrAI::boatMoveToNearLand(const tagInfo& info){
    //处理已移动的船，检测是否到达
    vector<int> arrivedBoats; //记录已到达的船（从集合中移除）
    for(int sn:movingBoatSNs){
        bool found=false;
        for(const tagFarmer& boat:info.farmers){
            if(boat.SN==sn){
                found=true;
                //若运输船变回空闲状态，看作到达
                if(boat.NowState==HUMAN_STATE_IDLE){
                    arrivedBoats.push_back(sn);
                }
                break;
            }
        }
        if(!found){
            arrivedBoats.push_back(sn); //船可能被销毁，强制移除
        }
    }
    //移除已到达的船
    for(int sn:arrivedBoats){
        movingBoatSNs.erase(sn);
        dockedBoatSNs.insert(sn);       //标记已停靠的运输船
    }
    //查找没有移动的运输船
    int targetBoatSN=-1;
    for(const tagFarmer& myBoat:info.farmers){
        if(myBoat.FarmerSort==1&&myBoat.NowState==HUMAN_STATE_IDLE&&!movingBoatSNs.count(myBoat.SN)&&!dockedBoatSNs.count(myBoat.SN)){
            targetBoatSN=myBoat.SN;
            break;
        }
    }
    pair<int,int> dockPos=findDockPos(info);
    int dockDR=dockPos.first;
    int dockUR=dockPos.second;
    //获取运输船坐标
    vector<pair<int,int>> boatPosition=getBoatPos(info);

    pair<int,int> nearLandPos=findNearLandPosForBoat(info,dockDR,dockUR,boatPosition);
    int nearLandDR=nearLandPos.first;
    int nearLandUR=nearLandPos.second;

    double nearLandx=nearLandDR*BLOCKSIDELENGTH+BLOCKSIDELENGTH/2.0;
    double nearLandy=nearLandUR*BLOCKSIDELENGTH+BLOCKSIDELENGTH/2.0;
    HumanMove(targetBoatSN,nearLandx,nearLandy);
    //加入移动集合
    movingBoatSNs.insert(targetBoatSN);
}
//#####################################运输船前往敌方大陆########################################
//根据已到达的战船位置获取敌岸沿海陆地坐标
pair<int,int> findNearLandPosInEnemy(const tagInfo& info,int ATshipDR,int ATshipUR,const vector<pair<int,int>>& usePos){
    const int findRange=11;         //搜索范围
    const int safeDistance=3;       //防止重叠的安全距离
    for(int x=ATshipDR-findRange; x<=ATshipDR+findRange;x++) {
        for (int y=ATshipUR-findRange;y<=ATshipUR+findRange;y++) {
            if(x<0||x>=128||y<0||y>=128) continue;  //越界检查
            if(gameM[x][y]=='-'||gameM[x][y]=='?'||gameM[x][y]=='P') continue;  //必须是陆地，排除海洋、渔场和未探索区域
            //避免与运输船重叠
            bool isOccupied=false;
            for(auto& pos:usePos){
                if(abs(x-pos.first)<safeDistance&&abs(y-pos.second)<safeDistance){
                    isOccupied=true;
                    break;
                }
            }
            if(isOccupied) continue;
            //避免与战船重叠
            bool isNearShip=false;
            for(const tagArmy& army:info.armies){
                if(army.Sort==7){  //判断是否是战船
                    int shipX=army.BlockDR;
                    int shipY=army.BlockUR;
                    if(abs(x-shipX)<=safeDistance&&abs(y-shipY)<=safeDistance){
                        isNearShip=true;
                        break;
                    }
                }
            }
            if(isNearShip) continue;
            //检查是否是沿海（周围有海洋块）
            bool isNearOcean=false;
            for(int i=x-1;i<=x+1;i++){
                for(int j=y-1;j<=y+1;j++){
                    if(i<0||i>=128||j<0||j>=128) continue;
                    if(i==x&&j==y) continue;        //跳过自身
                    if(gameM[i][j]=='-'){           //周围有海洋块
                        isNearOcean=true;
                        break;
                    }
                }
                if(isNearOcean) break;
            }

            //如果是沿海的陆地块，返回该位置
            if(isNearOcean){
                return {x, y};
            }
        }
    }
    //如果没有找到合适的位置，返回 {-1, -1}
    return {-1,-1};
}
//运输船前往敌方大陆并往返
void UsrAI::boatToEnemyLandAndReturn(const tagInfo& info){
    static unordered_set<int> toEnemyBoats;     //前往敌方大陆的船
    static unordered_set<int> atEnemyBoats;     //在敌方大陆已卸货的船
    static unordered_set<int> returnBoats;      //返回己方大陆的船
    //处理返回中的船只
    vector<int> arrivedHome;
    for(int sn:returnBoats){
        bool found=false;
        for(const tagFarmer& boat:info.farmers){
            if(boat.SN==sn){
                found=true;
                //判断是否回到己方大陆
                pair<int,int> dockPos=findDockPos(info);
                if(dockPos.first!=-1){
                    int distToDock=abs(boat.BlockDR-dockPos.first)+abs(boat.BlockUR-dockPos.second);
                    if(boat.NowState==HUMAN_STATE_IDLE&&distToDock<=10){
                        arrivedHome.push_back(sn);
                    }
                }
                break;
            }
        }
        if(!found) arrivedHome.push_back(sn); //船被毁
    }
    //移除已回到己方大陆的船
    for(int sn:arrivedHome){
        returnBoats.erase(sn);
        dockedBoatSNs.erase(sn);    //清除停靠标记，使其可以重新执行任务
    }
    //在敌方大陆已卸货的运输船返回己方大陆
    vector<int> toReturn;
    for(int sn:atEnemyBoats){
        bool found = false;
        for(const tagFarmer& boat:info.farmers){
            if(boat.SN==sn){
                found=true;
                if(boat.NowState==HUMAN_STATE_IDLE&&boat.Resource==0){
                    //船只空载且空闲，开始返回
                    pair<int,int> dockPos=findDockPos(info);
                    if(dockPos.first!=-1){
                        vector<pair<int,int>> boatPos=getBoatPos(info);
                        pair<int,int> homeLand=findNearLandPosForBoat(info,dockPos.first,dockPos.second,boatPos);
                        if(homeLand.first!=-1) {
                            double homeX=(homeLand.first+0.5)*BLOCKSIDELENGTH;
                            double homeY=(homeLand.second+0.5)*BLOCKSIDELENGTH;
                            HumanMove(sn,homeX,homeY);
                            toReturn.push_back(sn);
                        }
                    }
                }
                break;
            }
        }
        if(!found) toReturn.push_back(sn); // 船被毁
    }
    // 移动到返回集合
    for(int sn:toReturn){
        atEnemyBoats.erase(sn);
        returnBoats.insert(sn);
    }
    //处理前往敌方大陆的船只
    vector<int> arrivedEnemy;
    for(int sn:toEnemyBoats){
        bool found=false;
        for(const tagFarmer& boat:info.farmers){
            if(boat.SN==sn){
                found=true;
                if(boat.NowState==HUMAN_STATE_IDLE&&boat.Resource==0){
                    arrivedEnemy.push_back(sn); //运输船已卸货，到达敌方大陆
                }
                break;
            }
        }
        if(!found) arrivedEnemy.push_back(sn); //船被毁
    }

    for(int sn:arrivedEnemy){
        toEnemyBoats.erase(sn);
        atEnemyBoats.insert(sn);
    }
    //满载的运输船前往敌方大陆
    for(const tagFarmer& boat:info.farmers){
        if(boat.FarmerSort==1&&boat.NowState==HUMAN_STATE_IDLE&&boat.Resource>=5&&!toEnemyBoats.count(boat.SN)
                &&!atEnemyBoats.count(boat.SN)&&!returnBoats.count(boat.SN)){
            //查找战船位置
            int ATshipDR=-1,ATshipUR=-1;
            for(const tagArmy& myATship:info.armies) {
                if(myATship.Sort==AT_SHIP&&myATship.NowState==HUMAN_STATE_IDLE) {
                    ATshipDR=myATship.BlockDR;
                    ATshipUR=myATship.BlockUR;
                    break;
                }
            }
            if(ATshipDR!=-1){
                vector<pair<int,int>> boatPos=getBoatPos(info);
                pair<int,int> enemyLand=findNearLandPosInEnemy(info,ATshipDR,ATshipUR,boatPos);
                if(enemyLand.first!=-1){
                    double enemyX=(enemyLand.first+0.5)*BLOCKSIDELENGTH;
                    double enemyY=(enemyLand.second+0.5)*BLOCKSIDELENGTH;
                    HumanMove(boat.SN,enemyX,enemyY);
                    toEnemyBoats.insert(boat.SN);
                    boatToMoveFlag=true;
                    break;
                }
            }
        }
    }
}
//#########################################################################################################
//######################################市镇中心的动作##########################################
//市镇中心生产新的村民
void UsrAI::createFarmer(const tagInfo& info,int stage_human_max){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_CENTER&&building.Project==0&&info.Meat>=BUILDING_CENTER_CREATEFARMER_FOOD
           &&info.farmers.size()<=stage_human_max+fish_ship_Max){
            BuildingAction(building.SN,BUILDING_CENTER_CREATEFARMER);
        }
    }
}
//市镇中心升级时代
void UsrAI::updateAge(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_CENTER&&building.Project==0&&info.Meat>=500&&
                info.farmers.size()>=Stage0_humanMax){
            BuildingAction(building.SN,BUILDING_CENTER_UPGRADE);
        }
        break;
    }
}
//######################################市场的一些动作############################################
//升级伐木技术
void UsrAI::updateWood(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_MARKET&&building.Percent==100){
            if(info.Wood>=BUILDING_MARKET_WOOD_UPGRADE_WOOD&&info.Meat>=BUILDING_MARKET_WOOD_UPGRADE_FOOD){
                BuildingAction(building.SN,BUILDING_MARKET_WOOD_UPGRADE);
                updateWoodFlag=true;
            }
        }
    }
}
//提高农田容量
void UsrAI::updateFarm(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_MARKET&&building.Percent==100){
            if(info.Wood>=BUILDING_MARKET_FARM_UPGRADE_WOOD&&info.Meat>=BUILDING_MARKET_FARM_UPGRADE_FOOD){
                BuildingAction(building.SN,BUILDING_MARKET_FARM_UPGRADE);
                updateFarmFlag=true;
            }
        }
    }
}
//升级采集石头的技术
void UsrAI::updateStone(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_MARKET&&building.Percent==100){
            if(info.Stone>=BUILDING_MARKET_STONE_UPGRADE_STONE&&info.Meat>=BUILDING_MARKET_STONE_UPGRADE_FOOD){
                BuildingAction(building.SN,BUILDING_MARKET_STONE_UPGRADE);
                updateStoneFlag=true;
            }
        }
    }
}
//升级采集金矿的技术
void UsrAI::updateGold(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_MARKET&&building.Percent==100){
            if(info.Meat>=BUILDING_MARKET_GOLD_UPGRADE_FOOD&&info.Wood>=BUILDING_MARKET_GOLD_UPGRADE_WOOD){
                BuildingAction(building.SN,BUILDING_MARKET_GOLD_UPGRADE);
                updateGoldFlag=true;
            }
        }
    }
}
//######################################仓库的一些动作############################################
//仓库升级使用工具
void UsrAI::updateUsetool(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_STOCK&&building.Percent==100){
            if(info.Meat>=BUILDING_STOCK_UPGRADE_USETOOL_FOOD){
                BuildingAction(building.SN,BUILDING_STOCK_UPGRADE_USETOOL);
                UsetoolFlag=true;
            }
        }
    }
}
//仓库升级步兵护甲
void UsrAI::updateDefenseInfantry(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_STOCK&&building.Percent==100){
            if(info.Meat>=BUILDING_STOCK_UPGRADE_DEFENSE_INFANTRY_FOOD){
                BuildingAction(building.SN,BUILDING_STOCK_UPGRADE_DEFENSE_INFANTRY);
                DefenseInfantryFlag=true;
            }
        }
    }
}
//仓库升级弓兵护甲
void UsrAI::updateDefenceArcher(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_STOCK&&building.Percent==100){
            if(info.Meat>=BUILDING_STOCK_UPGRADE_DEFENSE_ARCHER_FOOD){
                BuildingAction(building.SN,BUILDING_STOCK_UPGRADE_DEFENSE_ARCHER);
                DefenseArcherFlag=true;
            }
        }
    }
}
//仓库升级骑兵护甲
void UsrAI::updateDefenceRider(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_STOCK&&building.Percent==100){
            if(info.Meat>=BUILDING_STOCK_UPGRADE_DEFENSE_RIDER_FOOD){
                BuildingAction(building.SN,BUILDING_STOCK_UPGRADE_DEFENSE_RIDER);
                DefenseRiderFlag=true;
            }
        }
    }
}
//##################################判断军营等建筑是否继续生产#####################################
//判断是否继续生产棍棒兵/斧头兵
bool isToCreateClubman(const tagInfo& info){
    bool toCreateClubmanFlag=false;
    int currentClubman_N=0;
    for(const tagArmy& ourClubman:info.armies){
        if(ourClubman.Sort==AT_CLUBMAN){
            currentClubman_N++;
        }
    }
    if(currentClubman_N<ClubmanMax){
        toCreateClubmanFlag=true;
    }
    return toCreateClubmanFlag;
}
//判断是否继续生产投石兵
bool isToCreateSlinger(const tagInfo& info){
    bool toCreateSlingerFlag=false;
    int currentSlinger_N=0;
    for(const tagArmy& ourSlinger:info.armies){
        if(ourSlinger.Sort==AT_SLINGER){
            currentSlinger_N++;
        }
    }
    if(currentSlinger_N<SlingerMax){
        toCreateSlingerFlag=true;
    }
    return toCreateSlingerFlag;
}
//判断是否继续生产弓箭兵
bool isToCreateBowman(const tagInfo& info){
    bool toCreateBowmanFlag=false;
    int currentBowman_N=0;
    for(const tagArmy& ourBowman:info.armies){
        if(ourBowman.Sort==AT_BOWMAN){
            currentBowman_N++;
        }
    }
    if(currentBowman_N<BowmanMax){
        toCreateBowmanFlag=true;
    }
    return toCreateBowmanFlag;
}
//判断是否继续生产骑兵
bool isToCreateScout(const tagInfo& info){
    bool toCreateScoutFlag=false;
    int currentScout_N=0;
    for(const tagArmy& ourScout:info.armies){
        if(ourScout.Sort==AT_SCOUT){
            currentScout_N++;
        }
    }
    if(currentScout_N<ScoutMax){
        toCreateScoutFlag=true;
    }
    return toCreateScoutFlag;
}
//#####################################军营等建筑生产军队#########################################
//军营生产棍棒兵/斧头兵
void UsrAI::ArmycampCreateClubman(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_ARMYCAMP&&building.Percent==100){
            if(building.Project==0&&isToCreateClubman(info)&&info.Meat>=BUILDING_ARMYCAMP_CREATE_CLUBMAN_FOOD){
                BuildingAction(building.SN,BUILDING_ARMYCAMP_CREATE_CLUBMAN);
                createClubmanFlag=true;
            }
        }
    }
}
//军营生产投石兵
void UsrAI::ArmycampCreateSlinger(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_ARMYCAMP&&building.Percent==100){
            if(building.Project==0&&isToCreateSlinger(info)
                    &&info.Stone>=BUILDING_ARMYCAMP_CREATE_SLINGER_STONE&&info.Meat>=BUILDING_ARMYCAMP_CREATE_SLINGER_FOOD){
                BuildingAction(building.SN,BUILDING_ARMYCAMP_CREATE_SLINGER);
                createSlingerFlag=true;
            }
        }
    }
}
//军营将棍棒兵升级为斧头兵
void UsrAI::ArmycampUpdateClubman(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_ARMYCAMP&&building.Percent==100){
            if(building.Project==0&&info.Meat>=BUILDING_ARMYCAMP_UPGRADE_CLUBMAN_FOOD){
                BuildingAction(building.SN,BUILDING_ARMYCAMP_UPGRADE_CLUBMAN);
                updateClubmanFlag=true;
            }
        }
    }
}
//靶场生产弓箭兵
void UsrAI::RangeCreateBowman(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_RANGE&&building.Percent==100){
            if(building.Project==0&&isToCreateBowman(info)&&info.Meat>=BUILDING_RANGE_CREATE_BOWMAN_FOOD
                    &&info.Wood>=BUILDING_RANGE_CREATE_BOWMAN_WOOD){
                BuildingAction(building.SN,BUILDING_RANGE_CREATE_BOWMAN);
                createBowmanFlag=true;
            }
        }
    }
}
//马厩生产骑兵
void UsrAI::StableCreateScout(const tagInfo &info){
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_STABLE&&building.Percent==100){
            if(building.Project==0&&isToCreateScout(info)&&info.Meat>=BUILDING_STABLE_CREATE_SCOUT_FOOD){
                BuildingAction(building.SN,BUILDING_STABLE_CREATE_SCOUT);
                createScoutFlag=true;
            }
        }
    }
}
//#########################################村民登船##############################################
//村民登船
void UsrAI::farmerBoardToBoat(const tagInfo &info){
    vector<int> suitableBoat;                                       //记录空闲且靠岸的运输船SN
    for(const tagFarmer& ourBoat:info.farmers){
        if(ourBoat.FarmerSort==1&&dockedBoatSNs.count(ourBoat.SN)
           &&ourBoat.NowState==HUMAN_STATE_IDLE&&ourBoat.Resource<5){
            suitableBoat.push_back(ourBoat.SN);
        }
    }
    if(suitableBoat.empty()){
        //DebugText("运输船未停靠或已载满，目前无可用运输船！");
        return;
    }
    vector<int> suitableForBoardFarmers;                            //记录适合登船的农民SN
    for(const tagFarmer& toBoardFarmer:info.farmers){
        if(toBoardFarmer.SN==firstDockBuilderSN){          
            continue;
        }
        if(toBoardFarmer.SN==firstHomeBuilderSN){
            continue;
        }
        if(toBoardFarmer.SN==firstHunterSN){
            continue;
        }
        if(toBoardFarmer.SN==firstCutterSN){
            continue;
        }
        if(toBoardFarmer.FarmerSort!=0) continue;
        if(toBoardFarmer.NowState!=HUMAN_STATE_IDLE) continue;
        if(boardingFarmers.count(toBoardFarmer.SN)) continue;

        suitableForBoardFarmers.push_back(toBoardFarmer.SN);
        boardingEnemyLandFarmer.push_back(toBoardFarmer);
    }
    //分配村民登船
    int farmerNumBoat=0;
    for(int boatSNs:suitableBoat){
        //查询当前运输船载人量
        int currentLoad=0;
        for(const tagFarmer& ourBoat:info.farmers){
            if(ourBoat.SN==boatSNs){
                currentLoad=ourBoat.Resource;
                break;
            }
        }
        while(currentLoad<5&&farmerNumBoat<suitableForBoardFarmers.size()){
            int farmerSN=suitableForBoardFarmers[farmerNumBoat];
            HumanAction(farmerSN,boatSNs);//登船            

            //标记为已下达命令
            boardingFarmers.insert(farmerSN);
            currentLoad++;
            farmerNumBoat++;
        }
    }
}
//########################################关于军队##############################################
//军队登船
void UsrAI::armyBoardToBoat(const tagInfo &info){
    vector<int> suitableBoat;                                       //记录空闲且靠岸的运输船SN
    for(const tagFarmer& ourBoat:info.farmers){
        if(ourBoat.FarmerSort==1&&dockedBoatSNs.count(ourBoat.SN)
           &&ourBoat.NowState==HUMAN_STATE_IDLE&&ourBoat.Resource<5){
            suitableBoat.push_back(ourBoat.SN);
        }
    }
    if(suitableBoat.empty()){
        //DebugText("运输船未停靠或已载满，目前无可用运输船！");
        return;
    }
    vector<int> suitableForBoardArmy;                               //记录适合登船的军队SN
    for(const tagArmy& toBoardArmy:info.armies){
        if(toBoardArmy.Sort==AT_SHIP) continue;//跳过战船
        if(toBoardArmy.NowState!=HUMAN_STATE_IDLE) continue;
        if(boardingArmys.count(toBoardArmy.SN)) continue;

        suitableForBoardArmy.push_back(toBoardArmy.SN);//存储适合登船的士兵
        boardingEnemyLandArmy.push_back(toBoardArmy);
    }
    //分配军队登船
    int armyNumBoat=0;
    for(int boatSNs:suitableBoat){
        //查询当前运输船运载数量
        int currentLoad=0;
        for(const tagFarmer& ourBoat:info.farmers){
            if(ourBoat.SN==boatSNs){
                currentLoad=ourBoat.Resource;
                break;
            }
        }
        while(currentLoad<5&&armyNumBoat<suitableForBoardArmy.size()){
            int armySN=suitableForBoardArmy[armyNumBoat];
            HumanAction(armySN,boatSNs);//登船
            //标记为已下达登船命令
            boardingArmys.insert(armySN);
            currentLoad++;
            armyNumBoat++;
        }
    }
}
//建造军营马厩靶场等建筑（以仓库为中心）
void UsrAI::buildArmyBuilding(const tagInfo &info,int targetBuildingType,int buildingNum){
    if(firstHomeBuilderSN!=-1){
        for(const tagFarmer& ArmyBuilder:info.farmers){
            if(ArmyBuilder.SN==firstHomeBuilderSN){
                if(ArmyBuilder.NowState==HUMAN_STATE_IDLE){
                    int x,y;
                    if(toBuildHome(x,y,BUILDING_STOCK,3,info)&&isGoWork(targetBuildingType,info,buildingNum)){
                        HumanBuild(ArmyBuilder.SN,targetBuildingType,x,y);
                    }
                }
            }
        }
    }
}
//陆军攻击敌军
void UsrAI::LandArmyFight(const tagInfo &info){
    vector<tagArmy>firstAttack;//优先攻击弓箭兵
    vector<tagArmy>secondAttack;
    for(const tagArmy& enemy:info.enemy_armies){
        if(enemy.Sort==AT_BOWMAN){
            firstAttack.push_back(enemy);
        }else if(enemy.Sort==AT_SHIP){
            continue;
        }else{
            secondAttack.push_back(enemy);
        }
    }
    for(const tagArmy& enemy:firstAttack){
        for(const tagArmy& ourArmy:info.armies){
            if((ourArmy.Sort==AT_CLUBMAN||ourArmy.Sort==AT_BOWMAN)&&(ourArmy.NowState==HUMAN_STATE_WALKING||ourArmy.NowState==HUMAN_STATE_IDLE)){
                HumanAction(ourArmy.SN,enemy.SN);
                //break;
            }
        }
    }
    if(firstAttack.empty()){
        for(const tagArmy& enemy:secondAttack){
            for(const tagArmy& ourArmy:info.armies){
                if(ourArmy.Sort==AT_CLUBMAN&&(ourArmy.NowState==HUMAN_STATE_WALKING||ourArmy.NowState==HUMAN_STATE_IDLE)){
                    HumanAction(ourArmy.SN,enemy.SN);
                    //break;
                }
            }
        }
    }
}
//骑兵去引敌军
void UsrAI::ScoutToFind(const tagInfo &info){
    int enemyLand_x=-1,enemyLand_y=-1;
    findEnermyRoute(info,enemyLand_x,enemyLand_y);
    for(const tagArmy& ourScout:boardingEnemyLandArmy){
        if(ourScout.Sort!=AT_SCOUT) continue;

        bool isReturn=false;//判断是否返回
        for(const tagArmy& enemy:info.enemy_armies){
            if(enemy.WorkObjectSN==ourScout.SN){
                isReturn=true;
                break;
            }
        }
        //如果被索敌则返回
        if(isReturn){
            //寻找我方战船
            int ourATshipDR=-1,ourATshipUR=-1;
            for(const tagArmy& ourATship:info.armies){
                if(ourATship.Sort==AT_SHIP){
                    ourATshipDR=ourATship.BlockDR;
                    ourATshipUR=ourATship.BlockUR;
                    break;
                }
            }
            //寻找战船附近的沿岸位置
            if(ourATshipDR!=-1&&ourATshipUR!=-1){
                vector<pair<int,int>> ScoutReturnPos;
                pair<int,int> returnPos=findNearLandPosInEnemy(info,ourATshipDR,ourATshipUR,ScoutReturnPos);
                int returnPosDR=returnPos.first;
                int returnPosUR=returnPos.second;
                if(returnPosDR!=-1&&returnPosUR!=-1){
                    HumanMove(ourScout.SN,returnPosDR*BLOCKSIDELENGTH,returnPosUR*BLOCKSIDELENGTH);
                    break;
                }
            }
            continue;
        }
        if(ourScout.NowState==HUMAN_STATE_IDLE){
            HumanMove(ourScout.SN,enemyLand_x*BLOCKSIDELENGTH,enemyLand_y*BLOCKSIDELENGTH);
            break;
        }
    }
}
//firstHunter建造完军营去打猎（瞪羚耗尽则砍树）
static bool ArmyFinishFlag=false;//判断马厩是否建成
void UsrAI::finishArmyToHunt(const tagInfo &info){
    //查找马厩是否建成
    for(const tagBuilding& building:info.buildings){
        if(building.Type==BUILDING_RANGE&&building.Percent==100){
            ArmyFinishFlag=true;
        }
    }
    if(firstHunterSN==-1) return;
    if(ArmyFinishFlag){
        for(const tagFarmer& farmer:info.farmers){
            if(farmer.SN==firstHunterSN&&farmer.NowState==HUMAN_STATE_IDLE){
                if(isGazelle(info)){
                    int nextGazelle=findResource(farmer,RESOURCE_GAZELLE,info);
                    if(nextGazelle!=-1){
                        HumanAction(farmer.SN,nextGazelle);
                    }
                }else{
                    int nextTreeSN=findResource(farmer,RESOURCE_TREE,info);
                    if(nextTreeSN!=-1){
                        HumanAction(farmer.SN,nextTreeSN);
                    }
                }
            }
            break;
        }
    }
}
//######################################AI接口(主函数)###########################################
void UsrAI::processData()
{
    tagInfo info=getInfo();                                     //获取每帧的信息
    realtimeMap(info);                                          //每帧获取一次实时地图
    init_map(info);                                             //资源映射更新
    judgeFarmerState(info);                                     //每帧更新一次村民状态
    //通过switch语句进行阶段划分
    switch(stage){
        case 0://资源累积##########################################################################################
            assignFirstTask(info);                              //初始任务分配
            buildDockToCut(info,1);                             //建造完一个船坞去砍树
            goWork_build_dock(info,2);                          //让起初建造船坞的继续
            buildDockToCut(info,2);                             //建造完两个船坞后去砍树
            goWork_build_home(info,4);                          //让起初建造房子的继续
            goWork_cut(info);                                   //初始砍树农民继续砍树
            goWork_hunt(info);                                  //初始打猎农民继续打猎
            assignNewTask(info);                                //分配新任务
            if(isToBuildFish_ship(info)){
                buildFish_ship(info);                           //建造渔船
            }
            ship_to_fish(info);                                 //渔船捕鱼
            ToBuildStock(info);                                 //建造仓库
            buildHomeToCut(info,4);                             //建造完stage0的房屋后去砍树
            createFarmer(info,Stage0_humanMax);                 //生产新的村民
            updateAge(info);                                    //市镇中心升级时代
            if(info.civilizationStage==CIVILIZATION_TOOLAGE){
                stage=1;
                DebugText("时代升级完成，进入stage1");
            }
            break;
        case 1://###################################################################################################
            goWork_cut(info);                                   //初始砍树农民继续砍树
            goWork_hunt(info);                                  //继续打猎
            farmerToHunt(info,2);                               //打猎
            goWork_build_dock(info,2);                          //如果第一阶段没有建造两个，则该阶段继续
            if(!isGoWork(BUILDING_DOCK,info,2)){
                buildDockToBuildhome(info,12);                  //建造12个房屋
            }

            if(!isGoWork(BUILDING_HOME,info,12)){
                buildDockToCut(info,2);                         //建造完12个房屋去砍树
            }
            assignNewTaskInStage1(info);                        //分配新任务
            createFarmer(info,Stage1_humanMax);                 //生产点人口
            ship_to_fish(info);                                 //渔船捕鱼
            if(isToBuildATShip(info)){
                buildATShip(info);                              //建造战船
            }
            fightingEnermy(info);                               //进攻敌方海军
            if(!isToBuildATShip(info)){
                toFight=true;
            }
            if(toFight){
                moveToEnermyLand(info);                         //战船寻路并攻击敌方战船
            }
            //战船出击后建造运输船
            if(isToBuildBoat(info)&&toFight){
                buildBoat(info);                                        //建造运输船
            }
            boatMoveToNearLand(info);                                   //运输船靠岸
            armyBoardToBoat(info);                                      //军队登船
            boatToEnemyLandAndReturn(info);                             //运输船前往敌方大陆并往返

            //如果渔船耗尽，则继续生产渔船
            if(isToBuildFish_ship(info)){
                buildFish_ship(info);                               //建造渔船
            }
            //建造一些高级建筑##############################################
            if(info.Wood>=BUILD_GRANARY_WOOD&&toFindTargetBuilding(BUILDING_ARMYCAMP,info)){
                buildNB_buildings(info,BUILDING_GRANARY,1);         //建造谷仓
            }
            if(info.Wood>=BUILD_MARKET_WOOD&&toFindTargetBuilding(BUILDING_GRANARY,info)){
                buildNB_buildings(info,BUILDING_MARKET,1);          //建造市场
            }
            if(toFindTargetBuilding(BUILDING_MARKET,info)){
                updateWood(info);                                   //升级伐木技术
            }
            if(info.Wood>=BUILD_FARM_WOOD&&toFindTargetBuilding(BUILDING_GRANARY,info)
               &&toFindTargetBuilding(BUILDING_MARKET,info)&&toFindTargetBuilding(BUILDING_RANGE,info)){
                 buildNB_buildings(info,BUILDING_FARM,1);           //建造农田
            }
            if(toFindTargetBuilding(BUILDING_MARKET,info)&&toFindTargetBuilding(BUILDING_FARM,info)){
                updateFarm(info);                                   //升级农田
            }
            //##########################################################
            //仓库升级士兵护甲
            if(toFindTargetBuilding(BUILDING_MARKET,info)){
                //仓库对有关技术进行升级，打造强大军队！
                if(!isToBuildATShip(info)&&DefenseInfantryFlag&&DefenseRiderFlag){
                    updateUsetool(info);                                    //仓库升级使用工具
                }
                if((!isToBuildATShip(info))){
                    updateDefenseInfantry(info);                            //仓库升级步兵护甲
                }
                if((!isToBuildATShip(info))&&DefenseInfantryFlag){
                    updateDefenceRider(info);                               //仓库升级骑兵护甲
                }
            }
            //############################建造军队建筑#######################
            //建造1个军营
            if(info.Wood>=BUILD_ARMYCAMP_WOOD){
                buildArmyBuilding(info,BUILDING_ARMYCAMP,1);
            }
            //建造1个马厩
            if(toFindTargetBuilding(BUILDING_ARMYCAMP,info)&&info.Wood>=BUILD_STABLE_WOOD){
                buildArmyBuilding(info,BUILDING_STABLE,1);
            }
            //建造1个靶场
            if(toFindTargetBuilding(BUILDING_STABLE,info)&&info.Wood>=BUILD_RANGE_WOOD){
                buildArmyBuilding(info,BUILDING_RANGE,1);
            }
            //##########################军队建筑有关动作#######################
            //军营将棍棒兵升级为斧头兵
            if(toFindTargetBuilding(BUILDING_ARMYCAMP,info)){
                ArmycampUpdateClubman(info);
            }
            //升级后军营开始生产斧头兵
            if(updateClubmanFlag&&toFindTargetBuilding(BUILDING_ARMYCAMP,info)){
                ArmycampCreateClubman(info);
            }
            //马厩生产骑兵
            if(toFindTargetBuilding(BUILDING_STABLE,info)){
                StableCreateScout(info);
            }
            //靶场生产弓箭兵
            if(toFindTargetBuilding(BUILDING_RANGE,info)){
                RangeCreateBowman(info);
            }
            //###############################################################
            if(toFight&&toFindTargetBuilding(BUILDING_ARMYCAMP,info)&&!isGoWork(BUILDING_HOME,info,12)){
                stage=2;
                DebugText("战船建造完毕，进入stage2，开始进攻敌方海军！");
            }
            break;
        case 2://##############################################################################################################
            //############################建造军队建筑#######################
            //建造1个军营
            if(info.Wood>=BUILD_ARMYCAMP_WOOD){
                buildArmyBuilding(info,BUILDING_ARMYCAMP,1);
            }
            //建造1个马厩
            if(toFindTargetBuilding(BUILDING_ARMYCAMP,info)&&info.Wood>=BUILD_STABLE_WOOD){
                buildArmyBuilding(info,BUILDING_STABLE,1);
            }
            //建造1个靶场
            if(toFindTargetBuilding(BUILDING_STABLE,info)&&info.Wood>=BUILD_RANGE_WOOD){
                buildArmyBuilding(info,BUILDING_RANGE,1);
            }
            //##########################军队建筑有关动作#######################
            //军营将棍棒兵升级为斧头兵
            if(toFindTargetBuilding(BUILDING_ARMYCAMP,info)){
                ArmycampUpdateClubman(info);
            }
            //升级后军营开始生产斧头兵
            if(updateClubmanFlag&&toFindTargetBuilding(BUILDING_ARMYCAMP,info)){
                ArmycampCreateClubman(info);
            }
            //马厩生产骑兵
            if(toFindTargetBuilding(BUILDING_STABLE,info)){
                StableCreateScout(info);
            }
            //靶场生产弓箭兵
            if(toFindTargetBuilding(BUILDING_RANGE,info)){
                RangeCreateBowman(info);
            }
            //建造一些高级建筑##############################################
            if(info.Wood>=BUILD_GRANARY_WOOD&&toFindTargetBuilding(BUILDING_ARMYCAMP,info)){
                buildNB_buildings(info,BUILDING_GRANARY,1);         //建造谷仓
            }
            if(info.Wood>=BUILD_MARKET_WOOD&&toFindTargetBuilding(BUILDING_GRANARY,info)){
                buildNB_buildings(info,BUILDING_MARKET,1);          //建造市场
            }
            if(toFindTargetBuilding(BUILDING_MARKET,info)){
                updateWood(info);                                   //升级伐木技术
            }
            if(info.Wood>=BUILD_FARM_WOOD&&toFindTargetBuilding(BUILDING_GRANARY,info)
                    &&toFindTargetBuilding(BUILDING_MARKET,info)&&toFindTargetBuilding(BUILDING_RANGE,info)){
                 buildNB_buildings(info,BUILDING_FARM,1);           //建造农田
            }
            //###############################技术升级#########################
            if(toFindTargetBuilding(BUILDING_MARKET,info)&&toFindTargetBuilding(BUILDING_FARM,info)){
                updateFarm(info);                                       //升级农田
            }
            if(updateFarmFlag&&toFindTargetBuilding(BUILDING_MARKET,info)){
                updateGold(info);                                       //升级采集金矿技术
            }
            if(toFindTargetBuilding(BUILDING_MARKET,info)){
                updateWood(info);                                       //升级伐木技术
            }
            //仓库升级士兵护甲
            if(toFindTargetBuilding(BUILDING_MARKET,info)){
                //仓库对有关技术进行升级，打造强大军队！
                if(DefenseInfantryFlag&&DefenseRiderFlag){
                    updateUsetool(info);                                    //仓库升级使用工具
                }
                if((!isToBuildBoat(info))){
                    updateDefenseInfantry(info);                            //仓库升级步兵护甲
                }
                if(DefenseInfantryFlag){
                    updateDefenceRider(info);                               //仓库升级骑兵护甲
                }
            }
            goWork_farming(info);                                       //种田的继续种田
            goWork_cut(info);                                           //继续砍树
            goWork_hunt(info);                                          //继续打猎
            //分配其他村民砍树
            farmerToCut(info,10);
            //###############################船的动作#########################
            //如果渔船耗尽，则继续生产渔船
            if(isToBuildFish_ship(info)){
                buildFish_ship(info);                           //建造渔船
            }
            //战船继续进攻
            fightingEnermy(info);                               //进攻敌方海军
            moveToEnermyLand(info);                             //不断地移动

            ship_to_fish(info);                                 //继续捕鱼
            //###############################################################
            if(info.Wood>=BUILD_FARM_WOOD&&(!toFindTargetBuilding(BUILDING_FARM,info))
                    &&toFindTargetBuilding(BUILDING_MARKET,info)&&toFindTargetBuilding(BUILDING_RANGE,info)){
                buildNB_buildings(info,BUILDING_FARM,1);                //农田耗尽时继续建造农田
            }
            if(!isGoWork(BUILDING_HOME,info,12)&&isGoWork(BUILDING_FARM,info,4)
                    &&toFindTargetBuilding(BUILDING_MARKET,info)&&toFindTargetBuilding(BUILDING_RANGE,info)){
                farmerToBuildFarmAfterStage0(info,4);                   //农田消耗完继续建造
            }

            //村民登船，运输船满载后出发
            if(isToBuildBoat(info)){
                buildBoat(info);                                        //建造运输船
            }
            boatMoveToNearLand(info);                                   //运输船靠岸

            armyBoardToBoat(info);                                      //军队上运输船
            //farmerBoardToBoat(info);                                    //村民上运输船
            boatToEnemyLandAndReturn(info);                             //运输船前往敌方大陆并往返

            LandArmyFight(info);                                        //我方陆军攻打敌方军队
            if(boatToMoveFlag&&!isToBuildBoat(info)&&DefenseRiderFlag&&updateGoldFlag){
                stage=3;
                DebugText("有关技术已升级,运输船前往敌方大陆，进入stage3！");
            }
            break;
        case 3://###################################################################################################
            //如果渔船耗尽，则继续生产渔船
            if(isToBuildFish_ship(info)){
                buildFish_ship(info);                                   //建造渔船
            }
            //村民登船，运输船满载后出发（如果stage2中有未完成动作）
            if(isToBuildBoat(info)){
                buildBoat(info);                                        //建造运输船
            }
            boatMoveToNearLand(info);                                   //运输船靠岸

            armyBoardToBoat(info);                                      //军队上运输船
            //farmerBoardToBoat(info);                                    //村民上运输船
            boatToEnemyLandAndReturn(info);                             //运输船前往敌方大陆并往返

            goWork_farming(info);                                       //继续种地
            //######################################船的动作#######################################
            //战船继续进攻
            fightingEnermy(info);                                       //战船继续保持攻击状态
            //moveToEnermyLand(info);                                     //战船移动

            //如果渔船耗尽，则继续生产渔船
            if(isToBuildFish_ship(info)){
                buildFish_ship(info);                                   //建造渔船
            }
            ship_to_fish(info);                                         //渔船继续捕鱼
            //######################################################################################
            //继续砍树
            farmerToCut(info,8);
            //继续打猎
            farmerToHunt(info,2);
            //采集金矿
            //farmerToGold(info);
            //采集石头
            farmerToStone(info,2);
            if(info.Wood>=BUILD_FARM_WOOD&&(!toFindTargetBuilding(BUILDING_FARM,info))
                    &&toFindTargetBuilding(BUILDING_MARKET,info)&&toFindTargetBuilding(BUILDING_RANGE,info)){
                buildNB_buildings(info,BUILDING_FARM,1);                //农田耗尽时继续建造农田
            }
            if(!isGoWork(BUILDING_HOME,info,12)&&isGoWork(BUILDING_FARM,info,4)
                    &&toFindTargetBuilding(BUILDING_MARKET,info)&&toFindTargetBuilding(BUILDING_RANGE,info)){
                farmerToBuildFarmAfterStage0(info,4);                   //农田消耗完继续建造
            }
            if(toFindTargetBuilding(BUILDING_MARKET,info)){
                updateDefenceArcher(info);
            }
            //建造一些高级建筑##############################################
            if(info.Wood>=BUILD_GRANARY_WOOD&&toFindTargetBuilding(BUILDING_ARMYCAMP,info)){
                buildNB_buildings(info,BUILDING_GRANARY,1);         //建造谷仓
            }
            if(info.Wood>=BUILD_MARKET_WOOD&&toFindTargetBuilding(BUILDING_GRANARY,info)){
                buildNB_buildings(info,BUILDING_MARKET,1);          //建造市场
            }
            if(toFindTargetBuilding(BUILDING_MARKET,info)){
                updateWood(info);                                   //升级伐木技术
            }
            if(toFindTargetBuilding(BUILDING_MARKET,info)&&toFindTargetBuilding(BUILDING_FARM,info)){
                updateFarm(info);                                   //升级农田
            }
            //############################建造军队建筑#######################
            //建造1个军营
            if(info.Wood>=BUILD_ARMYCAMP_WOOD){
                buildArmyBuilding(info,BUILDING_ARMYCAMP,1);
            }
            //建造1个马厩
            if(toFindTargetBuilding(BUILDING_ARMYCAMP,info)&&info.Wood>=BUILD_STABLE_WOOD){
                buildArmyBuilding(info,BUILDING_STABLE,1);
            }
            //建造1个靶场
            if(toFindTargetBuilding(BUILDING_STABLE,info)&&info.Wood>=BUILD_RANGE_WOOD){
                buildArmyBuilding(info,BUILDING_RANGE,1);
            }
            //##########################军队建筑有关动作#######################
            //军营将棍棒兵升级为斧头兵
            if(toFindTargetBuilding(BUILDING_ARMYCAMP,info)){
                ArmycampUpdateClubman(info);
            }
            //升级后军营开始生产斧头兵
            if(updateClubmanFlag&&toFindTargetBuilding(BUILDING_ARMYCAMP,info)){
                ArmycampCreateClubman(info);
            }
            //马厩生产骑兵
            if(toFindTargetBuilding(BUILDING_STABLE,info)){
                StableCreateScout(info);
            }
            //靶场生产弓箭兵
            if(toFindTargetBuilding(BUILDING_RANGE,info)){
                RangeCreateBowman(info);
            }
            if(toFindTargetBuilding(BUILDING_MARKET,info)){
                updateStone(info);
            }

            finishArmyToHunt(info);                                     //firstHunter建造完军事建筑后打猎（瞪羚耗尽后伐木）
            LandArmyFight(info);                                        //我方陆军攻击敌方陆军
    }
}
